package uk.co.hs.web.initializer;

import java.io.IOException;
import java.io.InputStream;
import java.util.jar.Attributes;
import java.util.jar.Manifest;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;

import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * Class to initialise the application (assuming Spring has already loaded
 * itself)
 */
public class VersionLoaderListener implements javax.servlet.ServletContextListener
{
 public static final String VERSION = "version";

 /**
  * Called when context is started
  *
  * @see javax.servlet.ServletContextListener#
  *      contextInitialized(javax.servlet.ServletContextEvent) {@inheritDoc}
  */
 public void contextInitialized(ServletContextEvent aEvent)
 {
   ServletContext context = aEvent.getServletContext();
   ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
   Resource manifestResource = ctx.getResource("/META-INF/MANIFEST.MF");
   String version = getAttribute(manifestResource);
   if (version == null)
   {
     version = "vDev";
   }
   aEvent.getServletContext().setAttribute(VERSION, version);

 }

 /**
  * Called when context is shut down
  *
  * @see javax.servlet.ServletContextListener#
  *      contextDestroyed(javax.servlet.ServletContextEvent) {@inheritDoc}
  */
 public void contextDestroyed(ServletContextEvent event)
 {
   }

 /**
  * Gets an attribute from the manifest file.
  *
  * @param aManifestResource Manifest file as a resource
  * @return The value of the required attribute or null if its not found.
  * @throws IOException If an IO error occurs.
  */
 private String getAttribute(Resource aManifestResource)
 {
   Manifest manifest = null;
   String version = null;
try{
   InputStream stream = aManifestResource.getInputStream();
   if (stream != null)
   {
     manifest = new Manifest(stream);
     Attributes atts = manifest.getMainAttributes();
     version = atts.getValue("Implementation-version");
   }
}
catch (IOException ioe)
{
}
   return version;
 }

}